package org.example.backend.service.impl;

import lombok.RequiredArgsConstructor;
import org.example.backend.dto.AnimalCategoryDTO;
import org.example.backend.entity.AnimalCategory;
import org.example.backend.repository.AnimalCategoryRepository;
import org.example.backend.service.AnimalCategoryService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AnimalCategoryServiceImpl implements AnimalCategoryService {

    private final AnimalCategoryRepository categoryRepository;

    @Override
    @Transactional
    public AnimalCategory createCategory(AnimalCategoryDTO categoryDTO) {
        AnimalCategory category = new AnimalCategory();
        category.setName(categoryDTO.getName());
        category.setDescription(categoryDTO.getDescription());
        return categoryRepository.save(category);
    }

    @Override
    @Transactional
    public AnimalCategory updateCategory(Long id, AnimalCategoryDTO categoryDTO) {
        AnimalCategory category = categoryRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("分类不存在"));
        
        category.setName(categoryDTO.getName());
        category.setDescription(categoryDTO.getDescription());
        return categoryRepository.save(category);
    }

    @Override
    @Transactional
    public void deleteCategory(Long id) {
        categoryRepository.deleteById(id);
    }

    @Override
    public AnimalCategory getCategory(Long id) {
        return categoryRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("分类不存在"));
    }

    @Override
    public List<AnimalCategory> getAllCategories() {
        return categoryRepository.findAll();
    }

    @Override
    public Page<AnimalCategory> getCategories(Pageable pageable) {
        return categoryRepository.findAll(pageable);
    }
} 